package routes

import (
	"ginadmin/models"
	"ginadmin/routes/context"
	"ginadmin/routes/handler"
	utils "ginadmin/utils"
	jwtgo "github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

func LoginForm(c *gin.Context) {
	request := c.Request
	username := request.FormValue("name")
	userpwd := request.FormValue("userpwd")

	handler.VerifyVal("用户名", username)
	handler.VerifyVal("密码", userpwd)

	u := &models.User{}
	err := u.FindByUsername(username)

	if err != nil {
		context.Err(c, 400, "用户不存在")
		return
	}

	if !utils.ComparePasswords(u.Password, []byte(userpwd)) {
		u.ErrorPwd()
		context.Err(c, 400, "用户名或密码错误")
		return
	}
	u.LoginSucc()
	generateToken(c, *u)
	//TODO 登录成功
	//context.Map(c, context.M{"code": 200, "msg": "OK", "data": u})
}

// 生成令牌
func generateToken(c *gin.Context, user models.User) {
	j := &utils.JWT{
		[]byte("wjgoadmin"),
	}
	claims := utils.CustomClaims{
		user.ID,
		user.UserName,
		user.Phone,
		jwtgo.StandardClaims{
			NotBefore: int64(time.Now().Unix() - 1000), // 签名生效时间
			ExpiresAt: int64(time.Now().Unix() + 3600), // 过期时间 一小时
			Issuer:    "wangjia",                       //签名的发行者
		},
	}

	token, err := j.CreateToken(claims)

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  err.Error(),
		})
		return
	}

	log.Println(token)

	//TODO 查询菜单
	role := models.Role{}
	err = role.FindById(user.Roleid)

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "没有该角色",
		})
		return
	}

	var menuinfo []models.Menu

	//如果是admin 返回全部
	if user.UserName == "admin" {
		//返回菜单
		menuinfo, err = models.MenuAll()
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": -1,
				"msg":  err.Error(),
			})
			return
		}
	} else {
		//返回菜单
		menuinfo, err = models.MenuListInMenuId(role.Auth)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": -1,
				"msg":  err.Error(),
			})
			return
		}
	}

	data := LoginResult{
		User:  user,
		Menu:  menuinfo,
		Token: token,
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功！",
		"data": data,
	})
	return
}

// LoginResult 登录结果结构
type LoginResult struct {
	Token string `json:"token"`
	Menu  []models.Menu
	models.User
}

// GetDataByTime 一个需要token认证的测试接口
func GetDataByTime(c *gin.Context) {
	claims := c.MustGet("claims").(*utils.CustomClaims)
	if claims != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "token有效",
			"data": claims,
		})
	}
}
